package com.mxpio.erp.inventory.controller;

import com.alibaba.excel.EasyExcel;
import com.mxpio.erp.common.enums.NoticeStatusEnums;
import com.mxpio.erp.common.inventory.entity.InitStockNotice;
import com.mxpio.erp.common.inventory.entity.InitStockNoticeLine;
import com.mxpio.erp.common.inventory.service.InitStockNoticeLineService;
import com.mxpio.erp.common.inventory.service.InitStockNoticeService;
import com.mxpio.erp.common.jpa.model.Notice;
import com.mxpio.erp.common.order.policy.NoticeContext;
import com.mxpio.erp.common.order.service.NoticeService;
import com.mxpio.erp.common.vo.OrderExcuteVo;
import com.mxpio.erp.inventory.policy.impl.InitStockNoticePolicy;
import com.mxpio.erp.inventory.service.UploadService;
import com.mxpio.erp.inventory.vo.InitStockNoticeImportModel;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.filestorage.entity.MxpioFileInfo;
import com.mxpioframework.filestorage.service.FileStorageService;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@Tag(name = "InitStockNoticeController", description = "初始库存通知单")
@RestController
@RequestMapping("/erp/inv/initstock/")
public class InitStockNoticeController {

    @Autowired
    private InitStockNoticeService service;
    @Autowired
    private InitStockNoticeLineService lineService;
    @Autowired
    private NoticeService noticeService;
    @Autowired
    private UploadService uploadService;

    @Resource(name = FileStorageService.BEAN_ID)
    private FileStorageService fileService;
    @GetMapping("list")
    @Operation(summary = "初始库存通知单列表", description = "获取初始库存通知单列表（无分页）", method = "GET")
    public Result<List<InitStockNotice>> list(@Parameter(description="查询参数") Criteria criteria) throws UnsupportedEncodingException {
        List<InitStockNotice> initStockNotice = service.list(InitStockNotice.class, criteria);
        return Result.OK(initStockNotice);
    }

    @GetMapping("page")
    @Operation(summary = "初始库存通知单列表", description = "获取初始库存通知单列表（分页）", method = "GET")
    public Result<Page<InitStockNotice>> page(@Parameter(description="查询参数") Criteria criteria, @Parameter(description="每页条数")Integer pageSize, @Parameter(description="页号")Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Page<InitStockNotice> initStockNotice = service.listPage(InitStockNotice.class, page, criteria);
        return Result.OK(initStockNotice);
    }

    @GetMapping("list/{noticeNo}")
    @Operation(summary = "根据noticeNo获取初始库存通知单", description = "根据noticeNo获取初始库存通知单", method = "GET")
    public Result<InitStockNotice> getById(@Parameter(description="业务单号") @PathVariable(name = "noticeNo", required = true) String noticeNo) {
        InitStockNotice initStockNotice = service.getById(InitStockNotice.class, noticeNo);
        return Result.OK(initStockNotice);
    }

    @RequestMapping("save")
    @Operation(summary = "保存初始库存通知单", description = "保存初始库存通知单", method = "POST")
    public Result<InitStockNotice> save(@RequestBody InitStockNotice notice) {
        return service.checkAndSave(notice);
        /*notice.setPickingType(NoticeStatusEnums.NoticeType.INIT_IN.getCode());//指定类型：初始入库
        service.save(notice,new SmartCrudPolicyAdapter(){
            @Override
            public boolean beforeInsert(CrudContext context) {
                Object o = context.getEntity();
                if(o instanceof InitStockNoticeLine){
                    InitStockNotice initStockNotice = context.getParent();
                    ((InitStockNoticeLine) o).setNoticeNo(initStockNotice.getNoticeNo());
                }
                return true;
            }
        });
        return Result.OK(notice);*/
    }
    
    @RequestMapping("excute/{noticeNo}")
    @Operation(summary = "通知单执行", description = "通知单执行")
    public Result<Object> excute(@PathVariable(name = "noticeNo", required = true) String noticeNo, 
    		@RequestBody OrderExcuteVo orderExcuteVo) {
    	InitStockNotice notice = service.getById(InitStockNotice.class, noticeNo);
        if (!StringUtils.equals(notice.getNoticeStatus(), NoticeStatusEnums.NoticeStatus.CREATE.getStatusCode())){
            return Result.error("仅开立状态允许执行确认！");
        }
    	NoticeContext context = noticeService.execute(notice, new InitStockNoticePolicy(orderExcuteVo.getLines()));
    	if(CollectionUtils.isEmpty(context.getErrors())) {
    		return Result.OK();
    	}else {
    		return Result.error(context.getErrors().get(0));
    	}
    }


    @DeleteMapping("remove/{noticeNos}")
    @Operation(summary = "根据noticeNo删除初始库存通知单", description = "删除初始库存通知单", method = "DELETE")
    public Result<InitStockNotice> remove(@Parameter(description="业务单号，多个单号用英文逗号分隔") @PathVariable(name = "noticeNos", required = true) String noticeNos) {
        String[] noticeNo = noticeNos.split(",");
        for(String key : noticeNo){
            Criteria c = Criteria.create().addCriterion("noticeNo", Operator.EQ, key);
            lineService.removeBatch(InitStockNoticeLine.class, c);//产出明细行
            service.delete(InitStockNotice.class, key);
        }
        return Result.OK();
    }
    
    @PutMapping("reject/{noticeNo}")
    @Operation(summary = "拒绝通知单", description = "拒绝通知单", method = "PUT")
    public Result<? extends Notice> close(@Parameter(description="通知单号") @PathVariable(name = "noticeNo", required = true) String noticeNo) {
    	InitStockNotice initStockNotice = service.getById(InitStockNotice.class,noticeNo);
    	return noticeService.updateNoticeStatus(initStockNotice, NoticeStatusEnums.NoticeStatus.REJECT);
    }


    @PostMapping("uploadInitStockNotice")
    @Operation(summary = "初始库存通知单模板导入", description = "初始库存通知单模板导入")
    public Result<?> uploadInitStockNotice(HttpServletRequest request) {
        try{
            MultipartHttpServletRequest multipartRequest =null;
            if (request instanceof MultipartHttpServletRequest) {
                multipartRequest = (MultipartHttpServletRequest)(request);
            }else {
                return Result.error("请在请求头中设置key:Content-Type,value:multipart/form-data");
            }
            MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
            List<InitStockNoticeImportModel> readModelList =  uploadService.uploadInitStockNotice(file.getInputStream());
            int yesSize = 0;
            int successSize = 0;
            int errorSize = 0;
            for (InitStockNoticeImportModel model : readModelList) {
                yesSize = yesSize + 1;
                if ("失败".equals(model.getImportSuccess())) {
                    errorSize = errorSize + 1;
                } else {
                    successSize = successSize + 1;
                }
            }
            String returnMsg = "";
            if (errorSize>0){
                returnMsg = "本次一共处理【"+ yesSize+ "】条，不通过【"+ errorSize+"】条，"+ "通过【"+ successSize+ "条】。具体失败原因请在下载的导入结果文件中查看。";
                String originalFilename = file.getOriginalFilename();
                String downloadFilename = originalFilename.substring(0,originalFilename.lastIndexOf("."))+"【导入结果】"+new Date().getTime();//
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                EasyExcel.write(byteArrayOutputStream, InitStockNoticeImportModel.class).sheet("导入结果").doWrite(readModelList);
                InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                MxpioFileInfo mxpioFileInfo = fileService.put("FileSystem", inputStream, downloadFilename+".xlsx",byteArrayOutputStream.size(),"");
                Result<Object> error = Result.error(returnMsg);
                error.setResult(mxpioFileInfo);
                return error;
            }else{
                returnMsg = "本次一共处理【"+ yesSize+ "】条，不通过【"+ errorSize+"】条，"+ "通过【"+ successSize+ "条】。";
                return Result.OK(returnMsg,readModelList);
            }
        } catch (Exception e) {
            return Result.error("导入失败");
        }
    }
}
